package com.ys.fmms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ys.fmms.exception.UserPasswordException;
import com.ys.fmms.mapper.UserMapper;
import com.ys.fmms.pojo.Role;
import com.ys.fmms.pojo.User;
import com.ys.fmms.pojo.UserRole;
import com.ys.fmms.service.UserRoleService;
import com.ys.fmms.service.UserService;
import com.ys.fmms.util.MD5;
import com.ys.fmms.util.ResultCodeEnum;
import com.ys.fmms.util.TimeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("userServiceImpl")
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleService userRoleService;

    @Override
    public User queryUser(String password, String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<User> getUserListByPage(Page<User> page, String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(userName)){
            queryWrapper.like("userName",userName);
        }
        queryWrapper.orderByAsc("id");
        IPage<User> iPage = baseMapper.selectPage(page,queryWrapper);
        return iPage;
    }

    @Override
    public void addOrModifyUser(User user, String userId) {
        if(StringUtils.hasText(userId)){
            user.setModifyTime(TimeUtils.currentDate());
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("id",userId);
            baseMapper.update(user,wrapper);
        }else{
            user.setCreateTime(TimeUtils.currentDate());
            user.setPassword(MD5.encrypt(user.getPassword()));
            baseMapper.insert(user);
        }
    }

    @Override
    public boolean checkCurrentUserPwd(String userId, String inputUserPwd) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("password");
        wrapper.eq("id",userId);
        String originPassword = baseMapper.selectOne(wrapper).getPassword();
        String inputPwd = MD5.encrypt(inputUserPwd).toLowerCase();
        if(!inputPwd.equals(originPassword)){
            return false;
        }
        return true;
    }

}
